package com.umeox.watch.prayertime.ui

import android.app.KeyguardManager
import android.content.ContentResolver
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.AudioManager
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.PowerManager
import android.os.Vibrator
import android.view.View
import android.view.Window
import android.widget.ImageView
import com.umeox.moto.common.log.Logger
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.umeox.moto.watch.themes.widget.TextView
import com.umeox.watch.moto.dataservice.DataProvider
import com.umeox.watch.prayertime.R
import com.umeox.watch.prayertime.base.BaseApp
import com.umeox.watch.prayertime.bean.PrayerAlarmDetail
import com.umeox.watch.prayertime.utils.Utils
import java.util.*

class PrayerTriggerActivity : ThemeAppCompatActivity() {


    private lateinit var prayerAlarmDetail: PrayerAlarmDetail
    private var mNameTv: TextView? = null
    private var mReminderOffsetTv: TextView? = null
    private var mMuteIv: ImageView? = null
    private var mCloseIv: ImageView? = null
    private var mView1: View? = null
    private var mView2: View? = null

    private var mSunriseTimeTv: TextView? = null

    private val pattern = longArrayOf(600, 600, 600, 600)
    private var vibrator: Vibrator? = null
    private var wakeLock: PowerManager.WakeLock? = null
    private var kl: KeyguardManager.KeyguardLock? = null

    private var mAudioManager: AudioManager? = null
    private var mMediaPlayer: MediaPlayer? = null
    private val stopCurrentAlarm = Runnable { finish() }
    private var mRingVolume = 0f
    private var mRingtoneUri: Uri? = null

    private var mHandler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Logger.e("===============onCreate=======================")
        setContentView(R.layout.activity_prayer_trigger)
        mAudioManager = getSystemService(AUDIO_SERVICE) as AudioManager
        mRingVolume =
            mAudioManager?.getStreamVolume(AudioManager.STREAM_MUSIC)!! * 1f / mAudioManager?.getStreamMaxVolume(
                AudioManager.STREAM_MUSIC
            )!!
        val acByte = intent.getByteArrayExtra(Utils.EXTRA_KEY_ID)
        acByte?.let {
            prayerAlarmDetail = Utils.toParcelable(it, PrayerAlarmDetail.CREATOR)
            Logger.e(prayerAlarmDetail.toString())
        } ?: run { finish() }


        initView()
        initData()

    }

    private fun initView() {
        mNameTv = findViewById(R.id.prayer_name_tv)
        mReminderOffsetTv = findViewById(R.id.reminder_offset_tv)
        mMuteIv = findViewById(R.id.mute_view)
        mCloseIv = findViewById(R.id.iv_close)
        mView1 = findViewById(R.id.fl_view1)
        mView2 = findViewById(R.id.rl_view2)

        mSunriseTimeTv = findViewById(R.id.sunrise_time_tv)
    }


    private fun initData() {

        wakeUpAndUnlock()
        enableHomeKeyDispatched(window, true)
        vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator

        if (prayerAlarmDetail.id != 1) {
            mView1?.visibility = View.VISIBLE
            mView2?.visibility = View.GONE
            mNameTv?.text = prayerAlarmDetail.prayerName
            if (prayerAlarmDetail.reminder == 0) {
                mReminderOffsetTv?.visibility = View.INVISIBLE
            } else {
                mReminderOffsetTv?.text = String.format(
                    Locale.ENGLISH,
                    getString(R.string.str_reminder_min),
                    prayerAlarmDetail.reminder
                )
            }
            mMuteIv?.setOnClickListener {
                finish()
            }

            initSoundPool()
            mHandler.postDelayed(stopCurrentAlarm, (20 * 1000).toLong())
        } else {
            mView1?.visibility = View.GONE
            mView2?.visibility = View.VISIBLE

            mSunriseTimeTv?.text = Utils.to24HourFormat(
                prayerAlarmDetail.prayerTime,
                Locale.getDefault()
            )
            mCloseIv?.setOnClickListener {
                finish()
            }
            mHandler.postDelayed(stopCurrentAlarm, (3 * 1000).toLong())
        }
    }

    private fun wakeUpAndUnlock() {
        if (kl == null) {
            val km = getSystemService(KEYGUARD_SERVICE) as KeyguardManager
            kl = km.newKeyguardLock("unLock")
        }
        //解锁
        kl!!.disableKeyguard()
        if (wakeLock == null) {
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            wakeLock = pm.newWakeLock(
                PowerManager.ACQUIRE_CAUSES_WAKEUP or PowerManager.FULL_WAKE_LOCK,
                javaClass.simpleName
            )
        }
        // 点亮亮屏
        wakeLock!!.acquire()
    }

    private fun enableHomeKeyDispatched(window: Window, enable: Boolean) {
        val lp = window.attributes
        if (enable) {
            lp.flags = lp.flags or -0x80000000
        } else {
            lp.flags = lp.flags and (-0x80000000).inv()
        }
        window.attributes = lp
    }

    private fun releaseLock() {
        if (wakeLock != null) {
            try {
                wakeLock!!.release()
            } catch (th: Throwable) {
                th.stackTrace
            }
        }
    }

    private fun initSoundPool() {
        var strAzan = DataProvider.getAzan()
        if (strAzan == null) {
            strAzan = "11111"
        }
        val azan: CharArray = strAzan.toCharArray()

        var index = prayerAlarmDetail.id
        if (index > 1) {
            index -= 1
        }

        vibrator!!.vibrate(pattern, 0)
        if (azan[index] == '1') {
            mAudioManager?.requestAudioFocus(
                mAudioFocusChangeListener,
                AudioManager.STREAM_ALARM,
                AudioManager.AUDIOFOCUS_GAIN_TRANSIENT
            )
            mRingtoneUri = getUriFromDrawableRes(this, R.raw.azan)

            playRingTone()
        }
    }


    /**
     * 得到资源文件中图片的Uri
     *
     * @param context 上下文对象
     * @param id      资源id
     * @return Uri
     */
    private fun getUriFromDrawableRes(context: Context, id: Int): Uri? {
        val resources = context.resources
        val path = (ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + resources.getResourcePackageName(id) + "/"
                + resources.getResourceTypeName(id) + "/"
                + resources.getResourceEntryName(id))
        return Uri.parse(path)
    }

    private fun playRingTone() {
        try {
            if (mMediaPlayer == null) {
                mMediaPlayer = MediaPlayer()
                mMediaPlayer?.setDataSource(this, mRingtoneUri!!)
                mMediaPlayer?.isLooping = true
                mMediaPlayer?.setAudioStreamType(AudioManager.STREAM_RING)
                mMediaPlayer?.prepare()
            }
            mMediaPlayer?.start()
        } catch (e: Exception) {
            e.stackTrace
        }
    }


    private val mAudioFocusChangeListener =
        AudioManager.OnAudioFocusChangeListener { focusChange ->
            when (focusChange) {
                AudioManager.AUDIOFOCUS_LOSS, AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                    stopRingTone()
                    if (vibrator != null) {
                        vibrator!!.cancel()
                    }
                }

                AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> mMediaPlayer!!.setVolume(
                    0.2f,
                    0.2f
                )

                AudioManager.AUDIOFOCUS_GAIN -> {
                    playRingTone()
                    mMediaPlayer!!.setVolume(mRingVolume, mRingVolume)
                    vibrator!!.vibrate(0)
                }
            }
        }

    private fun stopRingTone() {
        if (mMediaPlayer != null) {
            mMediaPlayer!!.stop()
            mMediaPlayer!!.release()
            mMediaPlayer = null
        }
    }


    override fun onDestroy() {
        Logger.e("===============onDestroy=======================")
        releaseLock()
        stopCurrentAlarm()
        BaseApp.getInstance().schedulePrayerTimeAlarm()
        mHandler.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    @Synchronized
    private fun stopCurrentAlarm() {
        mAudioManager!!.abandonAudioFocus(mAudioFocusChangeListener)
        stopRingTone()
        if (vibrator != null) {
            vibrator!!.cancel()
        }
        mHandler.removeCallbacks(stopCurrentAlarm)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        releaseLock()
    }

}
